package com.controller;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.entity.AllData;
import com.entity.User;
import com.util.DataSourceUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.util.DataSourceUtils;
import com.entity.News;
@WebServlet("/update")
public class UpdateServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        User manager=(User) session.getAttribute("user");
        if(manager==null)
        {
            req.getRequestDispatcher("/WEB-INF/jsp/login.jsp")
                    .forward(req, resp);
        }
        else{
            req.getRequestDispatcher("/WEB-INF/jsp/newsmanage.jsp")
                    .forward(req, resp);
        }
    }
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String op = req.getParameter("op");
        String id = req.getParameter("id");
        if(op.equals("更新")){
            try {
                Connection conn=DataSourceUtils.getConnection();
                String sql="UPDATE News set name=?,content=? WHERE id=?";
                PreparedStatement st=conn.prepareStatement(sql);
                st.setString(3, id);
                String name = req.getParameter("name");
                String content = req.getParameter("content");
                st.setString(1,name);
                st.setString(2,content);
                st.executeUpdate();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if(op.equals("新建")){
            try {
                Connection conn2=DataSourceUtils.getConnection();
                String name = req.getParameter("name");
                String content = req.getParameter("content");
                String sql="INSERT INTO News(name,content)VALUES(?,?)";
                PreparedStatement st2=conn2.prepareStatement(sql);
//                st2.setString(1, id);
                st2.setString(1, name);
                st2.setString(2, content);
                st2.executeUpdate();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        resp.sendRedirect(req.getContextPath() + "/newsmanage");
    }
}